import Com from '../../components/common'
import './style.scss'
import { useMemo ,useEffect,useState, useRef,useLayoutEffect} from "react";
import { getAllRoom,delRoom,addRoom, editRoom  }  from '../../api/room'
import { getAllBuild ,getBuildOne} from "../../api/build";
import { getAllType, getFloorOne } from "../../api/roomType";
import exportXLS from "../../until/exportXLS";
import {
    Button,
    Table,
    Drawer,
    Space,
    Form,
    Input,
    message,
    Modal,
    Cascader,
    Select,
    Radio,
    Pagination,
    Row,
    Col
} from "antd";



const Room = () => {

    const columns = useMemo(()=>[
        {title: '房间名称',dataIndex: 'roomName',key:'roomName'},
        {title: '楼栋楼层',dataIndex: 'BandF',key: 'BandF'},
        {title: '房型',dataIndex: 'roomStyle',key:'roomStyle'},
        {title: '内线电话',dataIndex: 'phone4in',key: 'phone4in',},
        {title: '外线电话',dataIndex: 'phone4out',key:'phone4out'},
        {
            title: '方向朝向', dataIndex: 'direction', key: 'direction',
            render: (_, record) => {
                return (
                    record.direction === '1' ?'东':record.direction==='2'?'南':record.direction==='3'?'西':'北'
                )
            }
        },
        {
            title: '是否有窗',
            dataIndex: 'hasWindow',
            key: 'hasWindow',
            render: (_, record) => {
                return (
                    record.hasWindow ?'是':'否'
                )
            }
        },
        {
            title: '是否靠近马路',
            dataIndex: 'isClose2Road',
            key: 'isClose2Road',
            render: (_, record) => {
                return (
                    record.isClose2Road ?'是':'否'
                )
            }
        },
        {
            title: '是否允许吸烟',
            dataIndex: 'isSmoke',
            key: 'isSmoke',
            render: (_, record) => {
                return (
                    record.isSmoke ?'是':'否'
                )
            }
        },
        {
            title: '是否噪音房',
            dataIndex: 'isNoise',
            key: 'isNoise',     
            render: (_, record) => {
                return (
                    record.isNoise ?'是':'否'
                )
            }
        },
        {
            title: '是否高温房',
            dataIndex: 'isHigh ',
            key: 'isHigh',
            render: (_, record) => {
                return (
                    record.isHigh ?'是':'否'
                )
            }
        },
        {
            title: '操作', dataIndex: '_id',
            render:(_, record)=>{ 
                return <> 
                            <Button  variant="outline" size="small" onClick={()=>confirm(record)}>删除</Button> 
                            <Button variant="outline" style={{ marginLeft: '5px' }} size="small"  onClick={()=>Edit(record)}>修改</Button> 
                        </>
            }
        },
    ], [])


     // 获取全部的楼栋信息
     const [ build,setBuild] = useState([])
     const getBuild = async ()=>{
         let res = await getAllBuild({});
         const temarr = res.data.map(item=>({
             label:item.name,
             value:item._id,
             children: item.floorInfo.map(it=>({ label:it,value:it }))
         }))
         setBuild(temarr)
     }
     useEffect(()=>{
         getBuild();
     }, [])
    
        // 获取全部的房型
        const [type,setType] = useState([]);
        const getTypes =  async ()=>{
            const res = await getAllType({limit:2000});
            setType(res.data.map(item=>({ label: item.name, value:item._id})))
        }
        useEffect(()=>{
            getTypes(); 
        },[])
    

    // 请示删除
    const confirm = (val) => {
        Modal.confirm({
          title: '删除',
          content: '确定删除吗??',
          okText: '确认',
            cancelText: '取消',
            onOk(){confirmDel(val)}
        });
      };

    //删除
    const confirmDel = async (value) => {
        let res = await delRoom({roomid:value._id});
        const  {success} = res;
        if(!success) return  message.error('删除失败');
        message.success('删除成功');
        getData();
    }

    //显示抽屉
    const [visible, setVisible] = useState(false);
    const showDrawer = () => {
        setVisible(true);
      };
    const onClose = () => {
        setVisible(false);
    };
    //添加房型
    const [roomadd] = Form.useForm()
    const onFinish = async (value) => {
        value.buildId = value.BandF[0]
        value.floor = value.BandF[1]
        value.type = value.roomStyle   
        let res = await addRoom(value);
        const { success } = res;
        if (!success) return   message.error('添加失败');
        message.success('添加成功');
        getData()
        roomadd.setFieldsValue({
                roomName: '',
                BandF: '',
                roomStyle: '',
                phone4in: '',
                phone4out: '',
                direction: 1,
                hasWindow: '',
                isClose2Road: '',
                isSmoke: '',
                isNoise: '',
                isHigh:''
           
        })
        setVisible(false);
    }
    const [data,setData] = useState([]);
    const [limit,setLimit] = useState(8);
    const [page,setPage] = useState(1); 
    const [total ,setTotal] = useState(0);

    // 获取全部数据
    const getData = async ()=>{
        const postData = { limit, page };     
        let res = await getAllRoom(postData)
        const { success, data, count } = res;
        const a = []     
        for (let item of data) {
            const buildInfo = await getBuildOne({ buildid: item.buildId })
            const roomS = await getFloorOne({ typeid: item.type })
            item.BandF = buildInfo.data.name + '/' + item.floor
            item.roomStyle = roomS.data.name
            item.key = item._id
            a.push(item)
        }
        if (success) {
            setData(a);
            setTotal(count)
        }; 
    }
    useLayoutEffect(()=>{
        getData();
    }, [limit, page])
    

    const [roomedit, setRoomedit] = useState(false);
    const [editRef] = Form.useForm()

    const onroomClose = () => {
        setRoomedit(false)
    }

    const Edit = value => {
        editRef.setFieldsValue(value)
        setRoomedit(true)
    }

    const editroon = async () => {
        let data = editRef.getFieldsValue()
        let a = data.BandF.split('/')
        data.floor = a[1]
        const r = await getAllBuild({ name: a[0] })
        for (let num in r) {
            if (num.name === a[0])
            data.buildId = num._id
        }
        const s = await getAllBuild({ name: data.roomStyle })
        for (let nm in s) {
            if (nm.name === data.roomStyle)
            data.type = nm.name
        }
        let res = await editRoom({
            ...data,
            roomid:data._id
        });
        const { success } = res;
        if (!success) return   message.error('修改失败');
        message.success('修改成功');
        getData()
        setRoomedit(false)
    }
    const changepage = (page,limit) => {
        setPage(page);
        setLimit(limit)
    }


    // 搜索功能
    const [inputValue, setInputValue] = useState('')
    
    const search = async() => {
        const postData = { limit, page ,roomName:inputValue};     
        let res = await getAllRoom(postData)
        const { success, data, count } = res;
        const a = []     
        for (let item of data) {
            const buildInfo = await getBuildOne({ buildid: item.buildId })
            const roomS = await getFloorOne({ typeid: item.type })
            item.BandF = buildInfo.data.name + '/' + item.floor
            item.roomStyle = roomS.data.name
            item.key = item._id
            a.push(item)
        }
        if (success) {
            setData(a);
            setTotal(count)
        }; 
    }
   
    
    const outPutData = [
        ['房间名称', '楼栋楼层','房型','内线电话','外线电话','方向朝向','是否有窗','是否靠近马路','是否允许吸烟','是否噪音房','是否高温房'],
        ...data.map(item => [
            item.roomName,
            item.BandF,
            item.roomStyle,
            item.phone4in,
            item.phone4out,
            item.direction === '1' ? '东' : item.direction === '2' ? '南' : item.direction === '3' ? '西' : '北',
            item.hasWindow?"是":"否",
            item.isClose2Road?"是":"否",
            item.isSmoke?"是":"否",
            item.isNoise?"是":"否",
            item.isHigh?"是":"否"
        ])
    ]

    return (
        <Com title="房间管理">
            <Row >
                <Col span={6}>  
                    <Button type="primary" onClick={showDrawer}>添加房间</Button>   
                </Col>
                <Col span={4}>
                    <Button type="primary" onClick={() => {exportXLS({ filename: '房间信息', data: outPutData })
                    }}>导出exel</Button>
                </Col>
                <Col span={6}>
                    <Input
                        placeholder="请输入要搜索的房间名称"
                        value={inputValue}
                        onChange={ (e)=>setInputValue(e.target.value)}
                    />
                </Col>
                <Col span={1}></Col>
                <Col span={7}>
                    <Button type="primary" onClick={search}>搜索</Button>
                </Col>
            </Row>
            <div>
                <Table
                    columns={columns}
                    dataSource={data}
                    rowKey={data._id}
                    pagination={
                        {
                            defaultPageSize: limit,
                            defaultCurrent:page,
                            total: total,
                            current:page,
                            onChange:changepage
                        }
                    }
                />
            </div>
            <Drawer
                title="房间的添加"
                placement="right"
                width={550}
                onClose={onClose}
                visible={visible}
                closable={false}
                
            >
                <Form
                    labelCol={{ span: 6, }}
                    wrapperCol={{ span: 15, }}
                    layout="horizontal"
                    initialValues={{
                        roomName: '',
                        BandF: '',
                        roomStyle: '',
                        phone4in: '',
                        phone4out: '',
                        direction: 1,
                        hasWindow: '',
                        isClose2Road: '',
                        isSmoke: '',
                        isNoise: '',
                        isHigh:''
                    }}
                    onFinish={onFinish}
                    form={ roomadd}
                >
                    <Form.Item
                        label="房间名称"
                        name="roomName"
                        rules={[
                            {
                                required: true,
                                message: '房间名称不能为空!',
                            },
                        ]}
                    >
                        <Input placeholder="请输入房间名称" />
                    </Form.Item>
                    <Form.Item
                        label="所在楼栋楼层"
                        name="BandF"
                        rules={[
                            {
                              required: true,
                              message: '楼栋楼层不能为空!',
                            },
                        ]}
                    >
                        <Cascader options={build} changeOnSelect />
                    </Form.Item>
                    <Form.Item
                        label="选择房型"
                        name="roomStyle"
                        rules={[
                            {
                              required: true,
                              message: '房型不能为空!',
                            },
                        ]}
                    >
                        <Select
                            options={type}
                        />
                    </Form.Item>
                    <Form.Item
                        label="内线电话"
                        name="phone4in"
                    >
                        <Input placeholder="请填写内线电话"/>
                    </Form.Item>
                    <Form.Item
                        label="外线电话"
                        name="phone4out"
                    >
                        <Input placeholder="请填写外线电话"/>
                    </Form.Item>
                    <Form.Item
                        label="方向朝向"
                        name="direction"
                        rules={[
                            {
                              required: true,
                              message: '方向朝向不能为空!',
                            },
                        ]}
                    >
                        <Radio.Group >
                            <Radio value={1}>东</Radio>
                            <Radio value={2}>南</Radio>
                            <Radio value={3}>西</Radio>
                            <Radio value={4}>北</Radio>
                        </Radio.Group>
                        
                    </Form.Item>
                    <Form.Item
                        label="是否有窗户"
                        name="hasWindow"
                        rules={[
                            {
                              required: true,
                              message: '窗户不能为空!',
                            },
                          ]}
                    >
                      <Radio.Group >
                            <Radio value={true}>是</Radio>
                            <Radio value={false}>否</Radio>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item
                        label="是否靠近马路"
                        name="isClose2Road"
                        rules={[
                            {
                              required: true,
                              message: '靠向不能为空!',
                            },
                          ]}
                    >
                        <Radio.Group>
                            <Radio value={true}>是</Radio>
                            <Radio value={false}>否</Radio>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item
                        label="是否允许吸烟"
                        name="isSmoke"
                        rules={[
                            {
                              required: true,
                              message: '是否允许吸烟不能为空!',
                            },
                          ]}
                    >
                        <Radio.Group>
                            <Radio value={true}>是</Radio>
                            <Radio value={false}>否</Radio>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item
                        label="是否噪音房"
                        name="isNoise"
                        rules={[
                            {
                              required: true,
                              message: '是否噪音房不能为空!',
                            },
                          ]}
                    >
                        <Radio.Group>
                            <Radio value={true}>是</Radio>
                            <Radio value={false}>否</Radio>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item
                        label="是否是高温房"
                        name="isHigh"
                        rules={[
                            {
                              required: true,
                              message: '是否高温房不能为空!',
                            },
                          ]}
                    >
                        <Radio.Group>
                            <Radio value={true}>是</Radio>
                            <Radio value={false}>否</Radio>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item >
                        <Button type="primary" onClick={onClose}>取消</Button>
                        <Button type="primary" htmlType="submit">立即添加</Button>
                    </Form.Item>

                </Form>
            </Drawer>
        
            <Drawer
                title="房型的修改"
                placement="right"
                width={500}
                onClose={onroomClose}
                visible={roomedit}
                closable={false}
            >
                <Form
                    labelCol={{ span: 6, }}
                    wrapperCol={{ span: 15, }}
                    layout="horizontal"
                    initialValues={{
                        roomName: '',
                        BandF: '',
                        roomStyle: '',
                        phone4in: '',
                        phone4out: '',
                        direction: '1',
                        hasWindow: '',
                        isClose2Road: '',
                        isSmoke: '',
                        isNoise: '',
                        isHigh:''
                    }}
                    onFinish={onFinish}
                    form={ editRef}
                >
                    <Form.Item
                        label="房间名称"
                        name="roomName"
                        rules={[
                            {
                                required: true,
                                message: '房间名称不能为空!',
                            },
                        ]}
                    >
                        <Input placeholder="请输入房间名称" />
                    </Form.Item>
                    <Form.Item
                        label="所在楼栋楼层"
                        name="BandF"
                        rules={[
                            {
                              required: true,
                              message: '楼栋楼层不能为空!',
                            },
                        ]}
                    >
                        <Cascader options={build} changeOnSelect />
                    </Form.Item>
                    <Form.Item
                        label="选择房型"
                        name="roomStyle"
                        rules={[
                            {
                              required: true,
                              message: '房型不能为空!',
                            },
                        ]}
                    >
                        <Select
                            options={type}
                        />
                    </Form.Item>
                    <Form.Item
                        label="内线电话"
                        name="phone4in"
                    >
                        <Input placeholder="请填写内线电话"/>
                    </Form.Item>
                    <Form.Item
                        label="外线电话"
                        name="phone4out"
                    >
                        <Input placeholder="请填写外线电话"/>
                    </Form.Item>
                    <Form.Item
                        label="方向朝向"
                        name="direction"
                        rules={[
                            {
                              required: true,
                              message: '方向朝向不能为空!',
                            },
                        ]}
                    >
                        <Radio.Group >
                            <Radio value='1'>东</Radio>
                            <Radio value='2'>南</Radio>
                            <Radio value='3'>西</Radio>
                            <Radio value='4'>北</Radio>
                        </Radio.Group>
                        
                    </Form.Item>
                    <Form.Item
                        label="是否有窗户"
                        name="hasWindow"
                        rules={[
                            {
                              required: true,
                              message: '窗户不能为空!',
                            },
                          ]}
                    >
                      <Radio.Group >
                            <Radio value={true}>是</Radio>
                            <Radio value={false}>否</Radio>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item
                        label="是否靠近马路"
                        name="isClose2Road"
                        rules={[
                            {
                              required: true,
                              message: '靠向不能为空!',
                            },
                          ]}
                    >
                        <Radio.Group>
                            <Radio value={true}>是</Radio>
                            <Radio value={false}>否</Radio>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item
                        label="是否允许吸烟"
                        name="isSmoke"
                        rules={[
                            {
                              required: true,
                              message: '是否允许吸烟不能为空!',
                            },
                          ]}
                    >
                        <Radio.Group>
                            <Radio value={true}>是</Radio>
                            <Radio value={false}>否</Radio>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item
                        label="是否噪音房"
                        name="isNoise"
                        rules={[
                            {
                              required: true,
                              message: '是否噪音房不能为空!',
                            },
                          ]}
                    >
                        <Radio.Group>
                            <Radio value={true}>是</Radio>
                            <Radio value={false}>否</Radio>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item
                        label="是否是高温房"
                        name="isHigh"
                        rules={[
                            {
                              required: true,
                              message: '是否高温房不能为空!',
                            },
                          ]}
                    >
                        <Radio.Group>
                            <Radio value={true}>是</Radio>
                            <Radio value={false}>否</Radio>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item name="_id">
                        <Button type="primary" onClick={onClose}>取消</Button>
                        <Button type="primary" onClick={editroon}>立即修改</Button>
                    </Form.Item>
                </Form>
            </Drawer>    
        </Com>
    )
}

export default Room